package com.example.day42_opengl_filter;

import android.graphics.SurfaceTexture;
import android.opengl.GLSurfaceView;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import androidx.camera.core.Preview;
import androidx.lifecycle.LifecycleOwner;

/**
 * Description:负责渲染的render
 * Created by Gdu on 2021/5/1 11:35.
 */

public class CameraRender implements GLSurfaceView.Renderer, Preview.OnPreviewOutputUpdateListener, SurfaceTexture.OnFrameAvailableListener {

    private CameraHelper cameraHelper;
    private CameraView cameraView;
    private SurfaceTexture mCameraTexture;
    private int[] textures;
    private ScreenFilter screenFilter;
    float[] mtx = new float[16];

    public CameraRender(CameraView cameraView) {
        this.cameraView = cameraView;
        LifecycleOwner lifecycleOwner = (LifecycleOwner) cameraView.getContext();
        //打开摄像头
        cameraHelper = new CameraHelper(lifecycleOwner,this);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        //让surfaceTexture和GPU共享一个数据源
        textures = new int[1];
        //把摄像头的数据传递给openGL
        mCameraTexture.attachToGLContext(textures[0]);
        //监听摄像头数据回调
        mCameraTexture.setOnFrameAvailableListener(this);
        screenFilter = new ScreenFilter(cameraView.getContext());
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        screenFilter.setSize(width,height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
//        Log.i("CameraRender", "onDrawFrame===当前线程是===" + Thread.currentThread().getName());
        //更新摄像头数据,取最新的数据
        mCameraTexture.updateTexImage();
        //获取texture的矩阵
        mCameraTexture.getTransformMatrix(mtx);
        //传递给screenFilter
        screenFilter.setTransformMatrix(mtx);
        screenFilter.onDraw(textures[0]);
    }

    //摄像头获取到的数据对象
    @Override
    public void onUpdated(Preview.PreviewOutput output) {
        mCameraTexture = output.getSurfaceTexture(); //摄像头预览到的数据对象
    }
    //摄像头数据
    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        cameraView.requestRender(); //有摄像头数据的时候请求openGL渲染  (其实最终就是调用上面的onDrawFrame)
    }
}
